﻿/// <reference path="../../tinymce/tiny_mce.js" />
/// <reference path="../../tinymce/tiny_mce.js" />
(function (window, undefined) {
    function cms() {
        this.addID = "#sectionAddContainer";
        this.addLinkID = "#sectionToggle";
        this.editFormID = "#editSections";
        this.editLinkClass = ".sectionEditLink";
        this.pageAddLinkClass = ".addPageLink";
        
        /* Some items for communication wtih the server */
        this.pageAddUrl = "/ControlPanel/Cms/Pages/";
        this.sectionEditURL = "/ControlPanel/Cms/Edit";
        
        
    }

    cms.prototype.wireup = function() {
        //$(this.addLinkID).click(this, function(obj) { obj.toggleSectionAdd(); });
        $(this.addLinkID).bind("click", { cms: this }, function(e) { e.data.cms.toggleSectionAdd(); });
        $(this.editLinkClass).bind("click", { cms: this }, function (e) { e.data.cms.createEditUi($(this).data("id")); });
        $(this.pageAddLinkClass).bind("click", { cms: this }, function (e) { e.data.cms.addPage($(this).data("id"));
            return false; });
        $(".pageResults").css("display", "none");
        $("#pageAddDialog").css("display", "none");
    };

    cms.prototype.toggleSectionAdd = function() {
        $(this.addID).toggle();
    };

    cms.prototype.package = function (id) {
        //console.log(id);
        var data = {};
        data["Id"] = id;
        this.selectById("td", id).each(function (index) {
            var $field = $(this).children("input").first();
            data[$field.attr("name")] = $field.val();
        });

        //console.log(data);

        this.async(data);
    };

    //cms.prototype.initTinyMCE = function (editorID) {
    //    console.log("Inside init tinyMCE function for editor " + editorID + " and the script path is ");
    //    tinyMCE.execCommand('mceAddControl', true, editorID);


    //}

    //cms.prototype.removeTinyMCE = function (editorID) {
    //    console.log("inside remove function for editoruid " + editorID);
    //    //tinyMCE.execCommand('mceFocus', false, editorID);
    //    tinyMCE.execCommand("mceRemoveControl", true, editorID);

    //}

    cms.prototype.addPage = function(id) {
        // TODO add logic
        //var result;
        //$.ajax({
        //    url: this.pageLoadURL + id,
        //    type: "GET",
        //}).done(function(data) {
        //    $("#pageResult_" + id).toggle().html(data);
        //});
        // Set the value to "" to avoid mistakes
        //$("#pageAddDialog > textarea").val("");
        // Set the attrribute of the id (TODO fix for better id)
        //var editorid = "page_for_section_" + id;
        //console.log(editorid);
        //$("#pageAddDialog > textarea").attr("id", editorid);
        //$("#pageAddDialog").dialog({
        //    modal: true,
        //    height: 300,
        //    width: 400,
        //    open: this.initTinyMCE(editorid),
        //    close : function(){
        //        window.cms.removeTinyMCE(editorid);
        //        $(this).dialog("destroy");
        //    },
        //    buttons: {
        //        "Dodaj!": function () { alert("clicked add!"); },
        //        "Odustani": function () {
        //            window.cms.removeTinyMCE(editorid);
        //            $(this).dialog("destroy");
        //        }
        //    }
        //});
        $("#pageAddDialog > #pageBody").load("/ControlPanel/Cms/Page/" + id);
        $("#pageAddDialog").modal();
        $("#pageAddSubmit").click(function () {
            $("#pageAddForm").submit();
        });
        /*$("#pageAddDialog").dialog({
            modal: true,
            height:750,
            width: 800,
            //open: this.initTinyMCE(editorid),
            close: function () {
                //window.cms.removeTinyMCE(editorid);
                $(this).dialog("destroy");
            },
            buttons: {
                "Dodaj!": function () {
                    console.log("clicked add!");

                    $("#pageAddForm").submit();
                },
                "Odustani": function () {
                    //window.cms.removeTinyMCE(editorid);
                    $(this).dialog("destroy");
                }
            }
        });*/

    };

    cms.prototype.async = function (data) {
        $.ajax({
            type: "POST",
            url: this.sectionEditURL,
            data: data,
            context : this
        }).done(function (adata) {
            //this.selectById("td", data.Id).each(function (index) {
            //    $(this).html(data[$(this).data("name")]);
            //});
            this.toggleEditUi(data.Id, data, false);
            this.toggleEditLink(data.Id, false);
            //alert(adata);
            //console.log(adata);
        });
    };

    cms.prototype.sync = function() {
    };
    


    //cms.prototype.createEditUi = function (linkobj) {
    //    var id = $(linkobj).attr("id");
    //    var realid = id.substring(id.indexOf("_")+1);
    //    var classname = ".editDiv_" + realid;

    //    $(classname).each(function(index) {
    //        $(this).html("<input type='text' name='model.bla' value='" + $(this).text() + "' class='section'/>");
    //    });
    //    $(linkobj).text("Save");
    //    $(linkobj).bind("click", { cms: this }, function(e) { e.data.cms.package(classname); });
    //};

    cms.prototype.createEditUi = function (id) {
        //var id = $(linkobj).data("id");

        //$("td").filter(function(index) {
        //    return $(this).data("id") == id;
        //}).each(function (index) {
        //    var name = $(this).data("name");
        //    $(this).html("<input type='text' name='"+name+"' value='" + $(this).text().trim() + "' class='section'/>");
        //});

        this.toggleEditUi(id, null, true);
        this.toggleEditLink(id, true);

    };
    
    /* UI and other special functions, consider these "private"
    // They encapsulate the logic to modify the elements of the UI.
    */

    /* Function to toggle the edit link and its behavior.
    */
    cms.prototype.toggleEditLink = function (id, flag) {
        var linkobj = $(".sectionEditLink").filter(function(index) { return $(this).data("id") == id; }).first();
        //var id = $(linkobj).data("id");
        if (flag) { // Toggle to "Save" + event handler
            $(linkobj).html("Save <i class='icon-save'></i>");
            $(linkobj).unbind("click");
            $(linkobj).bind("click", { cms: this }, function (e) { e.data.cms.package(id); });

        } else { // Toggle to "Edit" + event handler
            $(linkobj).html("Edit <i class='icon-edit'></i>");
            $(linkobj).unbind("click");
            $(linkobj).bind("click", { cms: this }, function (e) { e.data.cms.createEditUi(this); });

        }
    };
    
    /* Function to toggle the input UIs for a given ID. If true
    // it will create the input tags. If false, it will return the 
    // data back to the original state.
    */
    cms.prototype.toggleEditUi = function (id, data, flag) {
        if (flag) {
            this.selectById("td", id).each(function(index) {
                var name = $(this).data("name");
                $(this).html("<input type='text' name='" + name + "' value='" + $(this).text().trim() + "' class='section'/>");
            });
        } else {
            this.selectById("td", id).each(function(index) {
                $(this).html(data[$(this).data("name")]);

            });
        }
    };

    /* Function to select an element by an ID. Note that this function requires the 
    // existence of data-id tag (HTML5) on the element.
    */
    cms.prototype.selectById = function (element, id) {
        return $(element).filter(function (index) {
            return $(this).data("id") == id;
        });
    };

    // TODO add some stuff for dragging & droping

    window.cms = new cms();
})(this);